package com.shy.util.kq;

import org.apache.commons.codec.binary.Base64;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Objects;

public class Pkipair {

    //生成签名
    public String signMsg(String signMsg, String privateKey, String accessCode, String accessAlias) {
        String base64 = "";
        try {
            KeyStore ks = KeyStore.getInstance("PKCS12");
            //读取商家private key
            String file = Pkipair.class.getResource(privateKey).getPath().replaceAll("%20", " ");
            FileInputStream ksfis = new FileInputStream(file);
            BufferedInputStream ksbufin = new BufferedInputStream(ksfis);

            //访问证书的密码
            char[] keyPwd = accessCode.toCharArray();
            ks.load(ksbufin, keyPwd);

            //访问证书的别名
            PrivateKey priK = (PrivateKey) ks.getKey(accessAlias, keyPwd);
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(priK);
            signature.update(signMsg.getBytes(StandardCharsets.UTF_8));
            //sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            //base64 = encoder.encode(signature.sign());

            Base64 encoder = new Base64();
            base64 = encoder.encodeAsString(signature.sign());

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return base64;
    }

    //验证签名
    public boolean enCodeByCer(String val, String msg) {
        boolean flag = false;
        try {

            //快钱public key
            String file = Objects.requireNonNull(Pkipair.class.getResource("sandbox.publicKey.cer")).toURI().getPath();
            FileInputStream inStream = new FileInputStream(file);

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);

            PublicKey pk = cert.getPublicKey();

            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(pk);
            signature.update(val.getBytes());

            //sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            //System.out.println(new String(decoder.decodeBuffer(msg)));
            //flag = signature.verify(decoder.decodeBuffer(msg));

            Base64 decoder = new Base64();
            flag = signature.verify(decoder.decode(msg));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}